package com.gateio.flutter.lib_furnace

import android.content.Context
import androidx.annotation.Keep
import com.gateio.flutter.lib_furnace.protocol.GTFlutterRouteConfig
import com.google.gson.Gson
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.FlutterEngineGroup
import io.flutter.embedding.engine.dart.DartExecutor


/**
 * Author: Shper
 * Created: 2023/2/13
 */
@Keep
object GTFlutter {

    private lateinit var engineGroup: FlutterEngineGroup
    internal var pageStartedList: MutableList<String> = mutableListOf()

    /**
     * 初始化引擎组
     */
    internal fun initFlutterEngine(context: Context, preheatEngine: Boolean = false) {
        engineGroup = FlutterEngineGroup(context)
        // 预热一个引擎
//        if (preheatEngine) {
//            val options = FlutterEngineGroup.Options(context)
//            options.initialRoute = "preheat"
//            val flutterEngine = engineGroup.createAndRunEngine(options)
//            FlutterEngineCache.getInstance().put(options.initialRoute, flutterEngine)
//        }
    }

    /**
     * 通过 Builder 打开 Flutter
     */
    @JvmStatic
    fun withRouterName(routeName: String): GTFlutterBuilder {
        return GTFlutterBuilder(routeName)
    }

    /**
     * 判断是否 某一个 router 代表的页面是否在启动
     */
    @JvmStatic
    fun isPageStarted(routerName: String): Boolean {
        return pageStartedList.contains(routerName)
    }

//    /**
//     * 获取 FlutterEngine
//     */
//    @JvmStatic
//    @JvmOverloads
//    fun getRunningFlutterEngine(routerName: String,
//                                customEngineId: String? = null): FlutterEngine? {
//        customEngineId?.let {
//            return FlutterEngineCache.getInstance().get(it)
//        } ?: run {
//            return FlutterEngineCache.getInstance().get(routerName)
//        }
//    }

    /**
     * 创建或复用引擎
     */
    internal fun createAndRunEngine(
        context: Context,
        routerName: String,
        routeParams: Map<String, Any> = emptyMap(),
        customEngineId: String = "",
        transparentStatusBar: Boolean,
        extendMap: MutableMap<String, Any> = mutableMapOf(),
        customDarkMode: Boolean? = null
    ): String {
        val engineId = customEngineId.ifBlank { "$routerName:${System.currentTimeMillis()}" }
        // 添加扩展参数
        extendMap["customEngineId"] =  engineId
        extendMap["transparentStatusBar"] =  transparentStatusBar

        // 初始化相关参数
        val entrypointArgsList = if (routeParams.isNotEmpty()) {
            mutableListOf(
                GTFlutterInitializer.getEntrypointArgsJson(extendMap, customDarkMode),
                GTFlutterRouteConfig(Gson().toJson(routeParams)).toJsonString()
            )
        } else {
            mutableListOf(GTFlutterInitializer.getEntrypointArgsJson(extendMap, customDarkMode))
        }

        if (customEngineId.isNotBlank()) {
            val flutterEngine = FlutterEngineCache.getInstance().get(engineId)
            if (flutterEngine != null) {
                flutterEngine.dartExecutor.executeDartEntrypoint(
                    DartExecutor.DartEntrypoint.createDefault(),
                    entrypointArgsList
                )
                return engineId
            }
        }

        // 创建配置
        val options = FlutterEngineGroup.Options(context.applicationContext)
        options.initialRoute = routerName
        options.dartEntrypointArgs = entrypointArgsList
        // 自动注册 Plugins
        options.automaticallyRegisterPlugins = true
        // 不会每次创建，FlutterEngineGroup 会复用
        val flutterEngine = engineGroup.createAndRunEngine(options)
        // 注册通道
        GTFlutterInitializer.flutterEngineDelegate?.onFlutterEngineCreated(flutterEngine)
        // 加入到 FlutterEngineCache 中供 FlutterActivity、FlutterFragment 使用
        FlutterEngineCache.getInstance().put(engineId, flutterEngine)

        return engineId
    }

}
